package com.jlcloud.core.mp.plugins;

import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.DialectFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.IDialect;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.OracleDialect;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import com.jlcloud.core.mp.intercept.QueryInterceptor;

import java.sql.Connection;

/**
 * 拓展分页拦截器
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
@Setter
public class JlCloudPaginationInterceptor extends PaginationInnerInterceptor {

	/**
	 * 查询拦截器
	 */
	private QueryInterceptor[] queryInterceptors;

	@SneakyThrows
	@Override
	public boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
		QueryInterceptorExecutor.exec(queryInterceptors, executor, ms, parameter, rowBounds, resultHandler, boundSql);
		return super.willDoQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
	}

	@SneakyThrows
	@Override
	public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
		super.setDialect(autoDialect(executor));
		super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
	}

	/**
	 * 自动配置分页方言类的逻辑
	 *
	 * @param executor Executor
	 * @return 分页方言类
	 */
	@SneakyThrows
	protected IDialect autoDialect(Executor executor) {
		// 增加YashanDB方言
		Connection conn = executor.getTransaction().getConnection();
		if (conn.getMetaData().getURL().contains(":yasdb:")) {
			return new OracleDialect();
		} else {
			return DialectFactory.getDialect(JdbcUtils.getDbType(executor));
		}
	}

}
